package studio.xiaoyun.web.interceptor;

import java.lang.reflect.Method;
import java.util.List;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import studio.xiaoyun.core.parameter.Parameter;
import studio.xiaoyun.web.resource.Resource;

/**
 * {@link studio.xiaoyun.web.ResourceUtil ResourceUtil}类的拦截器，用于在方法正常执行后过滤多余的数据。
 * <p>本拦截器会拦截{@link studio.xiaoyun.web.ResourceUtil ResourceUtil}类中的方法，根据方法中的
 * {@link studio.xiaoyun.core.parameter.Parameter Parameter}参数的
 * {@link studio.xiaoyun.core.parameter.Parameter#getIncludeField() getIncludeField}方法判断如何删除多余的数据
 * @author 岳正灵
 */
@Aspect
@Component
public class ResourceUtilInterceptor {
	private Logger logger = LoggerFactory.getLogger(ResourceUtilInterceptor.class);
	
	@SuppressWarnings("rawtypes")
	@AfterReturning(pointcut="execution(* studio.xiaoyun.web.ResourceUtil.to*(..))",returning="refVal")
	public void doAfterReturning(JoinPoint joinPoint, Object refVal){
		Parameter parameter = null;
		for(Object obj : joinPoint.getArgs()){
			if(obj instanceof Parameter){
				parameter = (Parameter)obj;
				break;
			}
		}
		if(parameter !=null && refVal instanceof Resource){
			setNull((Resource)refVal,parameter);
		}else if(parameter !=null && refVal instanceof List){
			List list = (List)refVal;
			if(!list.isEmpty() && list.get(0) instanceof Resource){
				for(Object obj : list){
					setNull((Resource)obj,parameter);
				}
			}
		}
	}
	
	protected void setNull(Resource resource,Parameter parameter){
		List<String> fields = parameter.getIncludeField();
		Method[] methods = resource.getClass().getMethods();
		for(String field:fields){
			for(Method method:methods){
				if(method.getName().equalsIgnoreCase("set"+field) && method.getParameterCount()==1){
					try {
						Object param = null;
						method.invoke(resource, param);
					} catch (Exception e) {
						logger.warn("执行方法"+method.getName()+"时出错",e);
					}
					break;
				}
			}
		}
	}

}
